<template>
	<view
		class="layout"
		:style="{
			paddingTop: paddingTop,
			backgroundImage: 'url(' + pageBgImage + ')'
		}"
	>
		<view class="layout-main">
			<view class="layout-main-avatar">
				<image :src="isNew ? agentInfo.headImgUrl : userAvatar" />
				<text>{{ isNew ? agentInfo.nickNameA : '达人营注册' }}</text>
			</view>
			<image v-if="isNew" src="@/static/images/my/img_register_invite.png" class="remind-image" />
			<view
				class="layout-main-content"
				:style="{
					backgroundImage: 'url(' + pageMainImage + ')'
				}"
			>
				<view :key="index" v-for="(item, index) in mainContentList" class="layout-main-content-item">
					<view class="layout-main-content-item-left">
						{{ item.label }}
					</view>

					<view class="layout-main-content-item-right">
						<template v-if="item.input">
							<input
								type="textarea"
								:disabled="item.isSelect"
								:placeholder="item.placeholder"
								placeholder-class="placeholder"
								v-model="fromParams[item.type]"
								@click="changeSelectValue(item)"
							/>
							<image v-if="item.icon" :src="item.icon" />
						</template>

						<template v-if="item.textarea">
							<textarea placeholder-class="placeholder" :placeholder="item.placeholder" v-model="fromParams[item.type]" />
							<button @click="openTikTockLinkGuidance">如何获取链接？</button>
						</template>
					</view>
				</view>
			</view>
		</view>

		<BottomActionSheet
			v-model="isPopup"
			:list="channelList"
			:activeValue="channeValue"
			@changeBottomActionSheet="changeBottomActionSheet"
		/>

		<view class="layout-footer">
			<button :disabled="isLoading" :loading="isLoading" @click="getDouYinInfo" :class="{ active: isLoading }">获取帐号</button>
		</view>
	</view>
</template>

<script>
import { getBytedance } from '@/api/login';
import srorageKey from '@/utils/srorage/key';
import { getListChannelType } from '@/api/common';
import { getLocal, getSystemInfo, defaultImageUrl } from '@/utils';

import BottomActionSheet from '@/components/bottomActionSheet';
import { checkRegisterUrl } from '@/api/other';
const iconDown = Object.freeze(`${defaultImageUrl}icon/icon_register_down.png`);
const pageBgImage = Object.freeze(`${defaultImageUrl}image/img_register_bg.png`);
const pageMainImage = Object.freeze(`${defaultImageUrl}image/img_register_shape.png`);

const mainContentList = Object.freeze([
	{
		type: 'exhibitChanne',
		input: true,
		label: '推广平台',
		icon: iconDown,
		isSelect: true,
		placeholder: '请选择推广平台'
	},
	{
		type: 'channeUrl',
		textarea: true,
		label: '抖音链接',
		placeholder: '请输入抖音链接'
	}
]);

const { platform, statusBarHeight } = getSystemInfo();

export default {
	name: 'InfoRegistration',

	data() {
		return {
			pageBgImage,
			pageMainImage,

			mainContentList,

			isPopup: false,
			channelList: [],
			isLoading: false,

			fromParams: {
				channeUrl: '',
				channeValue: [],
				exhibitChanne: ''
			},
			getAUserId: '',
			checkResult: false,
			agentInfo: {},
			getPhone: ''
		};
	},

	computed: {
		userAvatar() {
			const { headUrl } = getLocal(srorageKey.userInfo) || {};

			return headUrl;
		},

		channeValue() {
			const {
				fromParams: { channeValue }
			} = this;

			return [channeValue[0]?.index || 0];
		},

		paddingTop() {
			return `${statusBarHeight + (platform === 'ios' ? 44 : 48)}px`;
		},

		isNew() {
			const { getAUserId = '', agentInfo = {} } = this;
			const { headImgUrl = '', nickNameA = '' } = agentInfo;
			console.log('isNew', getAUserId, nickNameA, headImgUrl);
			return getAUserId && headImgUrl && nickNameA;
		}
	},

	onLoad(options = {}) {
		const { aUserId = '', phone = '' } = options;
		this.getChannelList();
		if (aUserId) {
			this.getAUserId = aUserId;
			this.getPhone = phone;
			this.checkRegister(aUserId, phone);
		}
	},

	methods: {
		openTikTockLinkGuidance() {
			const imgUrl = `${defaultImageUrl}image/img_dylj.png`;
			// const webView = `${defaultImageUrl}webView/TikTockLinkGuidance.html`;
			// const url = `/tandianPage/CommonWebView?imgUrl=${imgUrl}&webView=${webView}`;

			const url = `/authorizePage/TikTockLinkGuidance?imgUrl=${imgUrl}`;

			uni.navigateTo({
				url
			});
		},

		changeSelectValue(params) {
			const { icon } = params;

			if (!icon) {
				return;
			}

			uni.hideKeyboard();
			this.isPopup = true;
		},

		getChannelList() {
			getListChannelType().then((res) => {
				const singleList = (res?.data || []).map((item) => {
					const { desc, value } = item;
					return {
						value: value,
						label: desc
					};
				});

				this.channelList = singleList;
			});
		},

		changeBottomActionSheet(value) {
			this.fromParams = {
				...this.fromParams,
				channeValue: value,
				exhibitChanne: value[0].label
			};
		},

		getDouYinInfo() {
			const { fromParams } = this;

			const status = mainContentList.some((item) => {
				if (fromParams[item.type].replace(/\s/g, '') === '') {
					uni.showToast({
						mask: true,
						icon: 'none',
						title: item.placeholder
					});
					return true;
				}
			});

			if (status) {
				return;
			}

			this.isLoading = true;
			getBytedance({ surl: fromParams.channeUrl })
				.then((res) => {
					const { data, code } = res;

					if (code !== 200) {
						return;
					}

					if (!data) {
						uni.showToast({
							mask: true,
							icon: 'none',
							title: '未找到对应抖音用户信息，请重试或检查链接是否正确'
						});
						return;
					}

					const { nickName, byteDanceId, followerCount } = data;
					const type = `${fromParams.channeValue[0].label}-${fromParams.channeValue[0].value}`;
					const { headImgUrl = '', nickNameA = '' } = this.agentInfo || {};
					const { getPhone = '' } = this;
					console.log(this.getAUserId, this.agentInfo);
					const url = `/authorizePage/InfoRegistration?nickName=${nickName}&byteDanceId=${byteDanceId}&followerCount=${followerCount}&type=${type}&aUserId=${this.getAUserId}&agentImg=${headImgUrl}&agentName=${nickNameA}&phone=${getPhone}`;

					uni.navigateTo({
						url
					});
				})
				.finally((e) => {
					this.isLoading = false;
				});
		},

		checkRegister(param = '', getPhone = '') {
			return new Promise((resolve, reject) => {
				const { phone = '' } = getLocal(srorageKey.userInfo) || {};
				checkRegisterUrl({ mobile: phone || getPhone, aUserId: param })
					.then((res = {}) => {
						// 是否已经注册：0-未注册，1-已注册
						const { blnRegister = '', headImgUrl = '', nickName = '' } = res.data || {};
						console.log(res);
						if (blnRegister || !headImgUrl || !nickName) {
							uni.switchTab({
								url: '/pages/tabBar/Index'
							});
						} else {
							this.checkResult = blnRegister; // 暂时未用
							this.agentInfo = { headImgUrl, nickNameA: nickName };
							resolve();
						}
					})
					.catch((err = {}) => {
						const { msg = '' } = err.data || {};
						uni.showToast({
							title: msg || '网络错误',
							icon: 'none'
						});
						reject();
					});
			});
		}
	},

	components: {
		BottomActionSheet
	}
};
</script>

<style lang="scss" scoped>
@import './components/channelCommon.scss';

.layout-main-content-item-right {
	button {
		color: #007eff;
		font-size: 24rpx;
		background: transparent;
		text-align: right;
		margin-top: 10rpx;
		padding-right: 0;

		&::after {
			display: none;
		}
	}
}
.remind-image {
	width: 100%;
	height: 160rpx;
	margin: 0 20rpx;
}
</style>
